package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.GradeBean;
import com.project.bean.LogBean;
import com.project.bean.RoleBean;
import com.project.bean.UserBean;
import com.project.mapper.IGradeMapper;
import com.project.mapper.ILogMapper;
import com.project.mapper.IRoleMapper;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

@Service
@Transactional
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserMapper userMapper;
    @Autowired
    private IRoleMapper roleMapper;
    @Autowired
    private IGradeMapper gradeMapper;
    @Autowired
    private ILogMapper logMapper;

    @Override
    public UserBean login(String username, String password) {
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        qw.eq("u_username", username);
        qw.eq("u_password", password);
        UserBean user = userMapper.selectOne(qw);

        if (user == null) {
            return null;
        }
        //查询角色集合
        List<RoleBean> roleList = roleMapper.findByUserId(user.getId());
        user.setRoleList(roleList);
        //获得角色id数组
        Integer[]  roleIdArr =  new Integer[roleList.size()];
        for (int i = 0; i < roleList.size(); i++) {
            roleIdArr[i]=roleList.get(i).getId();
        }

        //查询权限集合
        List<GradeBean> gradeList = gradeMapper.findByRoleList(roleIdArr);
        user.setGradeList(gradeList);

        //记录登陆日志
        logMapper.insert(getLog(user));

        return user;
    }

    @Override
    public void add(UserBean user,Integer[] roleIdArr) {
        //判断重名用户
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        qw.eq("u_username", user.getUsername());
        UserBean u = userMapper.selectOne(qw);
        if (u != null) {
            return;
        }
        //Md5加密处理
        String salt = this.getSalt();
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setSalt(salt);
        user.setPassword(md5Hash.toHex());

        userMapper.insert(user);
        userMapper.addRoles(user.getId(), roleIdArr);
    }

    @Override
    public void del(Integer id) {
        //删除用户角色
        userMapper.delRoles(id);
        //删除用户
        userMapper.deleteById(id);

    }

    @Override
    public void updateRole(Integer id, Integer[] roleIdArr) {
        //删除用户角色
        userMapper.delRoles(id);
        //批量添加用户角色
        userMapper.addRoles(id, roleIdArr);
    }

    @Override
    public IPage<UserBean> cutByItem(Integer pageNO, String realName) {
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        if (realName!=null&&!"".equals(realName)){
            qw.like("u_realName",realName);
        }
        return userMapper.selectPage(new Page<>(pageNO,5),qw);
    }


    @Override
    public UserBean findById(Integer id) {
        UserBean user = userMapper.selectById(id);
        //查询角色集合
        List<RoleBean> roleList = roleMapper.findByUserId(id);
        user.setRoleList(roleList);

        //获得角色id数组
        Integer[]  roleIdArr =  new Integer[roleList.size()];
        for (int i = 0; i < roleList.size(); i++) {
            roleIdArr[i]=roleList.get(i).getId();
        }

        //查询权限集合
        List<GradeBean> gradeList = gradeMapper.findByRoleList(roleIdArr);
        user.setGradeList(gradeList);

        return user;
    }


    @Override
    public void changePassword(Integer id, String password) {
        UserBean user = userMapper.selectById(id);

        //Md5加密处理
        String salt = this.getSalt();
        Md5Hash md5Hash = new Md5Hash(password, salt, 1024);
        user.setSalt(salt);
        user.setPassword(md5Hash.toHex());

        userMapper.updateById(user);

    }

    @Override
    public UserBean findByName(String username) {
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        qw.eq("u_username", username);
        UserBean user = userMapper.selectOne(qw);
        if(user!=null){
            //查询角色集合
            List<RoleBean> roleList = roleMapper.findByUserId(user.getId());
            user.setRoleList(roleList);
            //获得角色id数组
            Integer[]  roleIdArr =  new Integer[roleList.size()];
            for (int i = 0; i < roleList.size(); i++) {
                roleIdArr[i]=roleList.get(i).getId();
            }

            //查询权限集合
            List<GradeBean> gradeList = gradeMapper.findByRoleList(roleIdArr);
            user.setGradeList(gradeList);

            //记录登陆日志
            logMapper.insert(getLog(user));

            return user;
        }

        return null;
    }


    /**
     * 获取登陆用户的登陆日志
     *
     * @param user 用户对象
     * @return 日志对象
     */
    private LogBean getLog(UserBean user) {
        String time = LocalTime.now().toString();
        time = time.substring(0, time.lastIndexOf("."));

        String content = "用户 " + user.getRealName() + " 在 " + time + " 登陆系统";
        return new LogBean(content);
    }

    /**
     * 获取盐
     * @return
     */
    private String getSalt() {
        char[] array = new char[26];
        for (char i = 'a'; i <= 'z'; i++) {
            array[i - 'a'] = i;
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            sb.append(array[(int) (Math.random() * 26)]);
        }
        return sb.toString();
    }
}
